using System.Threading;
using System.Threading.Tasks;
using AutoMapper;
using MediatR;
using B.S.ReportEvent.ApiNew.Commands.Records;
using B.S.ReportEvent.ApiNew.Utils;
using B.S.ReportEvent.Domain.Entities;
using B.S.ReportEvent.ErrorCode;
using B.S.ReportEvent.ErrorCode.ErrorCodes;
using B.S.ReportEvent.Infrastructure.Interfaces;
using Microsoft.Extensions.Logging;

namespace B.S.ReportEvent.ApiNew.CommandHandlers.Records
{
    /// <summary>
    /// 新增审批记录命令处理器
    /// </summary>
    public class ProcessRecordInsertCommandHandler : IRequestHandler<ProcessRecordInsertCommand, ApiResult>
    {
        private readonly IProcessRecordsRepository _processRecordsRepository;
        private readonly IWfInstancesRepository _wfInstancesRepository;
        private readonly ILogger<ProcessRecordInsertCommandHandler> _logger;
        private readonly IHttpHelper _httpHelper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="processRecordsRepository">审批记录仓储</param>
        /// <param name="wfInstancesRepository">工作流实例仓储</param>
        /// <param name="logger">日志</param>
        /// <param name="httpHelper"></param>
        public ProcessRecordInsertCommandHandler(
            IProcessRecordsRepository processRecordsRepository,
            IWfInstancesRepository wfInstancesRepository,
            ILogger<ProcessRecordInsertCommandHandler> logger, IHttpHelper httpHelper)
        {
            _processRecordsRepository = processRecordsRepository;
            _wfInstancesRepository = wfInstancesRepository;
            _logger = logger;
            _httpHelper = httpHelper;
        }

        /// <summary>
        /// 处理新增审批记录命令
        /// </summary>
        /// <param name="request">命令</param>
        /// <param name="cancellationToken">取消标记</param>
        /// <returns>结果</returns>
        public async Task<ApiResult> Handle(ProcessRecordInsertCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 查询实例信息
                var instance = await _wfInstancesRepository.GetByIdAsync(request.InstanceId);
                if (instance == null)
                {
                    return ApiResult.Fail("实例不存在", StatusCodeEnum.Fail);
                }

                // 创建审批记录
                var record = new ProcessRecords
                {
                    InstanceId = request.InstanceId,
                    FormTypeNo = instance.FormTypeNo,
                    FormTypeName = instance.FormTypeName,
                    FormNo = instance.FormNo,
                    FormName = instance.FormName,
                    NodeNo = instance.CurrentNodeNo,
                    NodeName = instance.CurrentNodeName,
                    OperatorId = instance.CurrentOperatorId.ToString(),
                    OperatorName = instance.CurrentOperatorName,
                    OperatorOpinion = request.OperatorOpinion!,
                    ApproveStatus = request.ApproveStatus,
                    ApproveStatusName = request.ApproveStatus == 1 ? "通过" : "拒绝",
                    CreatedTime = DateTime.Now,
                    IsDeleted = 0
                };

                // 保存审批记录
                var result = await _processRecordsRepository.AddAsync(record);
                if (result <= 0)
                {
                    return ApiResult.Fail("新增审批记录失败", StatusCodeEnum.Fail);
                }

                // 更新实例状态（根据审批状态决定流程走向）
                if (request.ApproveStatus == 1) // 假设1表示通过，这里应该根据实际业务逻辑调整
                {
                    // 如果审批通过，更新实例状态为下一节点
                    instance.CurrentNodeNo = instance.NextNodeNo;
                    instance.CurrentNodeName = instance.NextNodeName;
                    instance.CurrentOperatorId = instance.NextOperatorId;
                    instance.CurrentOperatorName = instance.NextOperatorName;
               
                    //获取下一级节点
                    var nextNode = await _httpHelper.GetFormNodeByFormNo(instance.NextNodeNo);
                    if (!nextNode.Suc)
                    {
                        //rollback 事务
                        return ApiResult.Fail("审批失败", StatusCodeEnum.Fail);
                    }

                    //说明没有下一级了 结束流程
                    if (nextNode.FormNo == "")
                    {
                        instance.NextNodeNo = "";
                        instance.NextNodeName = "";
                        instance.NextOperatorId = 0;
                        instance.NextOperatorName = "";
                        instance.FlowStatus = 2; // 2表示结束
                        instance.FlowStatusName = "结束";
                    }
                    else
                    {
                        instance.NextNodeNo = nextNode.FormNo!;
                        instance.NextNodeName = nextNode.FormName!;
                        instance.NextOperatorId = nextNode.OperatorId;
                        instance.NextOperatorName = nextNode.OperatorName!;
                    }
                }
                else 
                {
                    // 如果审批拒绝，更新实例状态为结束
                    instance.FlowStatus = 1; // 1表示驳回 2代表结束
                    instance.FlowStatusName = "驳回";
                }

                instance.UpdatedTime = DateTime.Now;
                await _wfInstancesRepository.UpdateAsync(instance);

                return ApiResult.Success(StatusCodeEnum.Ok);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "新增审批记录异常");
                return ApiResult.Fail("新增审批记录异常: " + ex.Message, StatusCodeEnum.Exception);
            }
        }
    }
}